<template>
  <div class="example">
    <p class="example-title">
      <slot name="title"></slot>
    </p>
    <div class="example-content">
      <slot></slot>
    </div>
    <div class="example-code-collapse" @click="toggleCode">{{toggleLabel}}</div>
    <div class="example-code">
      <slot name="code"></slot>
    </div>
  </div>
</template>

<script>
const genUid = (len = 48) => {
  let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let charsLength = chars.length;
  let id = [];
  for (let i = 0; i < len; i++) {
    id[i] = chars.charAt(Math.random() * charsLength);
  }
  return `_${id.join('')}`;
};

export default {
  name: 'Example',
  data () {
    return {
      showCode: true,
      codeRealHeight: 0,
      codeHeight: 0
    };
  },
  methods: {
    toggleCode () {
      this.showCode = !this.showCode;
    }
  },
  computed: {
    toggleLabel () {
      return `点击${this.showCode ? '隐藏' : '显示'}代码`;
    }
  },
  mounted () {
    this.$el.setAttribute('id', genUid());
    this.$EventBus.$emit('ExampleHasSetId');
    let codeDom = this.$el.querySelector('.example-code');
    let toggleDom = this.$el.querySelector('.example-code-collapse');
    let codeHeight = codeDom.getBoundingClientRect().height;
    codeDom.style.height = codeHeight + 'px';
    codeDom.style.padding = '0 20px';
    codeDom.style.border = '1px solid #e2e2e2';
    let _this = this;
    toggleDom.addEventListener('click', function () {
      if (_this.showCode) {
        codeDom.style.height = codeHeight + 'px';
        codeDom.style.padding = '0 20px';
        codeDom.style.border = '1px solid #e2e2e2';
      } else {
        codeDom.style.height = 0;
        codeDom.style.border = 'none';
      }
    });
  }
};
</script>
